// pages/find/card/create-card.js
// var tcity = require("./citys.js");
const app = getApp();
const qiniu = require("../../utils/qiniu")
const getUser = require('../common/get-user')
// const qiniu = require("../../utils/qiniuCdn.js");

Page({
    data: {
        card: {}
    },
    onLoad: function(options) {
        qiniu.clearCache()
        this.setData({
            imgSize: parseInt((app.window.width - 20 - 30) / 4),
        })
        wx.showLoading({
            title: '加载中...',
        })

        Promise.all([
            getApp().http.get("city/member-card/card-detail"),
            getApp().http.get("city/member/qn-token"),
        ]).then(res => {
            const card = res[0].data.info.cityMemberCard || {}
            card.avatar = res[0].data.info.images
            if (card.province && card.city && card.county) {
                card.area = [card.province, card.city, card.county]
            } else {
                card.area = []
            }
            this.setData({
                card,
                imgs: card.cityMemberCardImages ? card.cityMemberCardImages.map(o => o.url) : []
            })
            card.img && qiniu.ignore(card.img)

            card.cityMemberCardImages && card.cityMemberCardImages.forEach(o => {
                qiniu.ignore(o.url)
            })
            getUser(false).then(user => {
                this.setData({
                    noAuth: false
                })
                qiniu.ignore(user.avatarUrl)
                !this.data.card.img && this.setData({
                    "card.img": user.avatarUrl,
                })
            }).catch(err => {
                this.setData({
                    noAuth: true
                })
            })
            this.setData({
                qiniuToken: res[1].data
            })
            wx.hideLoading()
        })

        wx.login({
            success: res => {
                this.code = res.code
            }
        })
    },
    /**
     * 修改二维码
     */
    chooseCode() {
        wx.chooseImage({
            count: 1,
            success: res => {
                this.setData({
                    "card.wx_qr": res.tempFilePaths[0]
                })
                qiniu.upload(res.tempFilePaths[0], this.data.qiniuToken).then(res => {
                    return qiniu.upload(this.data.card.wx_qr, this.data.qiniuToken)
                }).then(keys => {
                    wx.showLoading({
                        title: '上传中...',
                    })
                    return getApp().http.post("city/tiny-station/change-member-card", {
                        data: {
                            wx_qr: keys[0]
                        },
                    }).then(res => {
                        console.log('88888')
                        wx.hideLoading()
                    })
                }).catch(err => {
                    this.loading = false
                })
                // qiniu.upload(res.tempFilePaths[0], this.data.qiniuToken).then(keys => {
                //     console.log(keys, 'keys')
                //     wx.showLoading({
                //         title: '上传中...',
                //     })
                //     return getApp().http.post("city/tiny-station/change-member-card", {
                //         data: {
                //             wx_qr: 'http://img.zhxcxmall.com/' + keys[0]
                //         },
                //     }).then(res => {
                //         console.log('88888')
                //         wx.hideLoading()
                //     })
                // })
            }
        })
    },
    showMore() {
        this.setData({
            isMore: !this.data.isMore
        })
    },

    onArea(evt) {
        this.setData({
            "card.area": evt.detail.value
        })
    },

    submit(evt) {
        if (this.loading) {
            return
        }
        this.loading = true
        const post = evt.detail.value
        console.log(post)
        if (post.area && post.area.length) {
            post.province = post.area[0]
            post.city = post.area[1]
            post.county = post.area[2]
        }
        post.is_open = post.is_open ? 1 : 0
        post.lng = this.data.card.lng || ""
        post.lat = this.data.card.lat || ""

        wx.showLoading({
            title: '保存中...',
        })

        qiniu.upload(this.data.imgs, this.data.qiniuToken).then(res => {
            post.images = res || []
            return qiniu.upload(this.data.card.img, this.data.qiniuToken)
        }).then(keys => {
            post.img = keys[0] + ""
            post.id = this.data.card.id || ""
            const [procince, city, county] = this.data.card.area
            console.log(post)
            getApp().http.post(`city/member-card/${post.id ? "update" : "create"}`, {
                data: post
            }).then(res => {
                wx.hideLoading()
                wx.navigateBack({

                })
                this.loading = false
            }).catch(err => {
                this.loading = false
            })
        }).catch(err => {
            this.loading = false
        })
    },
    chooseAvatar() {
        wx.chooseImage({
            count: 1,
            success: res => {
                this.setData({
                    "card.img": res.tempFilePaths[0]
                })
            }
        })
    },

    chooseImage() {
        const {
            imgs = []
        } = this.data
        wx.chooseImage({
            success: res => {
                imgs.push(...res.tempFilePaths)
                this.setData({
                    imgs
                })
            },
        })
    },
    dropImg(evt) {
        const {
            index
        } = evt.currentTarget.dataset
        const {
            imgs
        } = this.data
        wx.showActionSheet({
            itemList: ['删除'],
            success: res => {
                res.tapIndex == 0 && imgs.splice(index, 1) && this.setData({
                    imgs
                })
            }
        })
    },
    preImg(evt) {
        const {
            index
        } = evt.currentTarget.dataset
        const {
            imgs
        } = this.data
        wx.previewImage({
            current: imgs[index],
            urls: imgs,
        })
    },

    getPhoneNumber(evt) {
        evt.detail.encryptedData && getApp().http.post("city/member/get-phone", {
            header: {
                "Encrypted-Data": evt.detail.encryptedData,
                "IV": evt.detail.iv,
                "Code": this.code
            },
            showMsg: false
        }).then(p => {
            this.setData({
                userPhone: p.data,
                'card.phone': p.data
            })
        })
    },

    setUserPhone() {
        this.setData({
            'card.phone': this.data.userPhone
        })
    },

    openMap() {
        wx.chooseLocation({
            success: res => {
                this.setData({
                    'card.address': res.address,
                    'card.lng': res.longitude,
                    'card.lat': res.latitude
                })
            }
        })
    }
})